package cn.tedu.syn;

import java.util.concurrent.locks.ReentrantReadWriteLock;

/**本类用于读写锁入门案例*/
public class TestSaleTickets {
    public static void main(String[] args) {
        SaleTickets target = new SaleTickets();
        Thread t1 = new Thread(target);
        Thread t2 = new Thread(target);
        Thread t3 = new Thread(target);
        Thread t4 = new Thread(target);
        t1.start();
        t2.start();
        t3.start();
        t4.start();
    }
}
class SaleTickets implements Runnable{
    int tickets = 100;
    static ReentrantReadWriteLock lock = new ReentrantReadWriteLock(true);
    @Override
    public void run() {
        while(true) {
            //2.在操作共享资源前上锁
            lock.writeLock().lock();
            try {
                if(tickets > 0) {
                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + "=" + tickets--);
                }
                if(tickets <= 0) break;
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                //3.finally{}中释放锁,注意一定要手动释放,防止死锁,否则就独占报错了
                lock.writeLock().unlock();
            }
        }
    }
}